from fastapi import APIRouter, Depends, Request, Form, HTTPException, File, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse  
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
import os
import uuid
from backend.models.models import FollowUpRecord, Diagnosis, Advice, User
from backend.dependencies import get_db
from backend.routers.admin import get_current_admin  # 修正导入路径
from fastapi import HTTPException, Depends, Request
from fastapi.responses import RedirectResponse

router = APIRouter()
# 删除这里的 templates 定义，将由 main.py 提供


def get_current_user(request: Request, db: Session = Depends(get_db)):
    username = request.cookies.get("user")
    if not username:
        raise HTTPException(status_code=401, detail="未登录")

    user = db.query(User).filter(User.username == username).first()
    if not user:
        raise HTTPException(status_code=401, detail="用户不存在")

    return username

# 定义一个可选的管理员依赖项
async def get_current_admin_optional(request: Request, db: Session = Depends(get_db)):
    try:
        return get_current_admin(request, db)
    except HTTPException:
        return None

@router.get("/add_record", response_class=HTMLResponse)
async def add_record_form(
    request: Request,
    user: str = Depends(get_current_user),
    admin: User = Depends(get_current_admin_optional),
    db: Session = Depends(get_db)
):
    # 获取当前用户信息
    current_user = db.query(User).filter(User.username == user).first()
    return templates.TemplateResponse("add_record.html", {
        "request": request,
        "is_admin": admin is not None,
        "current_user": current_user
    })

@router.post("/add_record")
async def add_record(
    request: Request,
    doctor_name: str = Form(...),
    patient_name: str = Form(...),  # 添加患者姓名参数
    advice_deepseek: str = Form(None),
    advice_huatuo: str = Form(None),
    left_eye_image: UploadFile = File(None),
    right_eye_image: UploadFile = File(None),
    db: Session = Depends(get_db),
    user: str = Depends(get_current_user)
):
    # 验证医生是否存在
    doctor = db.query(User).filter(User.username == doctor_name).first()
    if not doctor:
        return templates.TemplateResponse("add_record.html", {
            "request": request,
            "error": "医生不存在，请检查医生姓名",
            "is_admin": await get_current_admin_optional(request, db) is not None,
            "current_user": db.query(User).filter(User.username == user).first()
        })

    # 验证患者是否存在
    patient = db.query(User).filter(User.username == patient_name).first()
    if not patient:
        return templates.TemplateResponse("add_record.html", {
            "request": request,
            "error": "患者不存在，请检查患者姓名",
            "is_admin": await get_current_admin_optional(request, db) is not None,
            "current_user": db.query(User).filter(User.username == user).first()
        })

    # 处理文件上传
    left_eye_image_path = None
    right_eye_image_path = None
    static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "static", "images")
    os.makedirs(static_dir, exist_ok=True)

    if left_eye_image:
        # 生成唯一文件名
        file_ext = left_eye_image.filename.split(".")[-1]
        file_name = f"left_eye_{uuid.uuid4()}.{file_ext}"
        file_path = os.path.join(static_dir, file_name)
        
        # 保存文件
        with open(file_path, "wb") as f:
            f.write(await left_eye_image.read())
            
        left_eye_image_path = f"/static/images/{file_name}"

    if right_eye_image:
        # 生成唯一文件名
        file_ext = right_eye_image.filename.split(".")[-1]
        file_name = f"right_eye_{uuid.uuid4()}.{file_ext}"
        file_path = os.path.join(static_dir, file_name)
        
        # 保存文件
        with open(file_path, "wb") as f:
            f.write(await right_eye_image.read())
            
        right_eye_image_path = f"/static/images/{file_name}"

    # 创建随访记录 - 使用患者用户名作为外键
    new_record = FollowUpRecord(
        username=patient.username,  # 使用患者用户名
        doctor_name=doctor_name,    # 医生用户名
        left_eye_image=left_eye_image_path,
        right_eye_image=right_eye_image_path
    )
    db.add(new_record)
    db.commit()
    db.refresh(new_record)

    # 获取所有诊断信息并创建诊断记录
    form_data = await request.form()
    diagnosis_count = 0
    while f"diagnosis_name_{diagnosis_count}" in form_data:
        diagnosis_name = form_data[f"diagnosis_name_{diagnosis_count}"]
        diagnosis_risk = form_data[f"diagnosis_risk_{diagnosis_count}"]
        
        new_diagnosis = Diagnosis(
            record_id=new_record.id,
            name=diagnosis_name,
            risk_level=diagnosis_risk
        )
        db.add(new_diagnosis)
        diagnosis_count += 1

    # 创建DeepSeek建议记录
    if advice_deepseek:
        new_advice_deepseek = Advice(
            record_id=new_record.id,
            source="deepseek",
            content=advice_deepseek
        )
        db.add(new_advice_deepseek)

    # 创建华佗建议记录
    if advice_huatuo:
        new_advice_huatuo = Advice(
            record_id=new_record.id,
            source="huatuo",
            content=advice_huatuo
        )
        db.add(new_advice_huatuo)

    db.commit()

    # 根据用户角色决定重定向路径
    is_admin = await get_current_admin_optional(request, db) is not None
    if is_admin:
        return RedirectResponse(url="/admin/dashboard", status_code=302)
    else:
        return RedirectResponse(url="/dashboard", status_code=302)

@router.get("/logout")
async def logout():
    response = RedirectResponse(url="/login")
    response.delete_cookie("user", path="/")  # 添加path参数
    return response

@router.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request, db: Session = Depends(get_db), user: str = Depends(get_current_user)):
    # 获取当前用户信息
    current_user = db.query(User).filter(User.username == user).first()
    
    # 根据用户角色查询不同的记录
    if current_user.role == "doctor":
        # 医生查看自己负责的记录
        records = db.query(FollowUpRecord).filter(FollowUpRecord.doctor_name == user).order_by(FollowUpRecord.date.desc()).all()
    else:
        # 患者查看自己的记录
        records = db.query(FollowUpRecord).filter(FollowUpRecord.username == user).order_by(FollowUpRecord.date.desc()).all()
    
    # 添加调试信息
    print(f"当前用户: {user}")
    print(f"用户角色: {current_user.role}")
    print(f"查询到的记录数量: {len(records)}")
    
    return templates.TemplateResponse("dashboard.html", {
        "request": request,
        "user": user,
        "records": records
    })

@router.get("/debug_records")
async def debug_records(db: Session = Depends(get_db), user: str = Depends(get_current_user)):
    records = db.query(FollowUpRecord).filter(FollowUpRecord.username == user).all()
    return {
        "user": user,
        "records_count": len(records),
        "records": [{
            "id": record.id,
            "username": record.username,
            "doctor_name": record.doctor_name,
            "date": str(record.date)
        } for record in records]
    }


@router.get("/record/{record_id}", response_class=HTMLResponse)
async def record_detail(
    request: Request,
    record_id: int,
    db: Session = Depends(get_db),
    user: str = Depends(get_current_user),
    admin: User = Depends(get_current_admin_optional)  # 使用可选的管理员依赖项
):
    # 查询记录
    record = db.query(FollowUpRecord).filter(FollowUpRecord.id == record_id).first()
    
    if not record:
        raise HTTPException(status_code=404, detail="记录不存在")
    
    # 获取当前用户信息
    current_user = db.query(User).filter(User.username == user).first()
    
    # 权限检查
    if admin is None:
        if current_user.role == "doctor":
            if record.doctor_name != user:
                raise HTTPException(status_code=403, detail="无权访问此记录")
        else:
            # 患者角色
            if record.username != user:
                raise HTTPException(status_code=403, detail="无权访问此记录")
    
    # 准备模板数据
    record_data = {
        "id": record.id,
        "patient_name": record.username,  # 添加患者名称
        "doctor": record.doctor_name,
        "date": record.date,
        "left_eye_url": record.left_eye_image or "/static/images/default_left_eye.jpg",
        "right_eye_url": record.right_eye_image or "/static/images/default_right_eye.jpg",
        "diagnoses": [{
            "name": diag.name,
            "risk_level": diag.risk_level
        } for diag in record.diagnoses],
        "advice_deepseek": next((adv.content for adv in record.advices if adv.source == "deepseek"), "无DeepSeek建议"),
        "advice_huatuo": next((adv.content for adv in record.advices if adv.source == "huatuo"), "无华佗建议")
    }
    
    return templates.TemplateResponse("record_detail.html", {
        "request": request,
        "record": record_data,
        "is_admin": admin is not None,
        "user": user  # 添加user变量
    })

@router.get("/record_json/{record_id}")
async def record_detail_json(
    record_id: int,
    db: Session = Depends(get_db),
    user: str = Depends(get_current_user),
    admin: User = Depends(get_current_admin_optional)
):
    # 查询记录
    record = db.query(FollowUpRecord).filter(FollowUpRecord.id == record_id).first()
    
    if not record:
        raise HTTPException(status_code=404, detail="记录不存在")
    
    # 获取当前用户信息
    current_user = db.query(User).filter(User.username == user).first()
    
    # 权限检查
    if admin is None:
        if current_user.role == "doctor":
            if record.doctor_name != user:
                raise HTTPException(status_code=403, detail="无权访问此记录")
        else:
            # 患者角色
            if record.username != user:
                raise HTTPException(status_code=403, detail="无权访问此记录")
    
    # 准备JSON数据
    record_data = {
        "id": record.id,
        "patient_name": record.username,
        "doctor": record.doctor_name,
        "date": str(record.date),
        "left_eye_url": record.left_eye_image or "/static/images/default_left_eye.jpg",
        "right_eye_url": record.right_eye_image or "/static/images/default_right_eye.jpg",
        "diagnoses": [{
            "name": diag.name,
            "risk_level": diag.risk_level
        } for diag in record.diagnoses],
        "advice_deepseek": next((adv.content for adv in record.advices if adv.source == "deepseek"), "无DeepSeek建议"),
        "advice_huatuo": next((adv.content for adv in record.advices if adv.source == "huatuo"), "无华佗建议")
    }
    
    return record_data

@router.get("/test")
async def test_route():
    return {"message": "Test route working"}

@router.post("/delete_record/{record_id}")
async def delete_record(record_id: int, db: Session = Depends(get_db), user: str = Depends(get_current_user)):
    # 获取当前用户信息
    current_user = db.query(User).filter(User.username == user).first()
    
    # 查询要删除的记录
    record = db.query(FollowUpRecord).filter(FollowUpRecord.id == record_id).first()
    
    # 验证记录是否存在
    if not record:
        raise HTTPException(status_code=404, detail="记录不存在")
    
    # 权限检查：医生只能删除自己创建的记录，管理员可以删除所有记录
    if current_user.role != "admin" and record.doctor_name != user:
        raise HTTPException(status_code=403, detail="没有权限删除此记录")
    
    # 删除记录（级联删除会自动删除相关的诊断和建议记录）
    db.delete(record)
    db.commit()
    
    # 重定向回dashboard页面
    return RedirectResponse(url="/dashboard", status_code=303)